package com.ai.platform.system.web;

import com.ai.platform.common.util.AiPlatformUtil;
import com.ai.platform.core.context.InvocationContextHolder;
import com.ai.platform.model.dto.Input;
import com.ai.platform.model.dto.Output;
import com.ai.platform.model.vo.UserVo;
import com.ai.platform.system.entity.SysUser;
import com.ai.platform.core.annotation.AIController;
import com.ai.platform.core.constant.IConstants;
import com.ai.platform.core.controller.BaseController;
import com.alibaba.fastjson.JSON;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

@AIController
public class LoginController extends BaseController{

    private final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    DefaultKaptcha defaultKaptcha;


    /**
     * 登录页
     * @return
     */
    @GetMapping(value = "/login")
    public String toLogin(){
        return "login";
    }

    /**
     * 用户登录
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public Output doLoginIn(@Valid UserVo userVo, HttpServletRequest httpServletRequest){
        Output output=new Output();
        output.setCode(IConstants.FIELD_VALID_ERROR);
        String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode");
        if(!captchaId.equals(userVo.getCode())){
            output.setMsg("验证码不正确！");
            return output;
        }
        String account = userVo.getAccount();
        UsernamePasswordToken token = new UsernamePasswordToken(account, userVo.getPassword());
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(token);
        }catch (IncorrectCredentialsException ice){
            logger.info("对账号【" + account +"】进行登录验证，验证未通过，错误的凭证！");
            output.setMsg("账号或密码不正确！");
        }catch(UnknownAccountException uae){
            logger.info("对账号【" + account +"】进行登录验证，验证未通过，未知账户！");
            output.setMsg("未知账户！！");
        }catch(LockedAccountException lae){
            logger.info("对账号【" + account +"】进行登录验证，验证未通过，账户锁定！");
            output.setMsg("账户已锁定！");
        }catch(ExcessiveAttemptsException eae){
            logger.info("对账号【" + account +"】进行登录验证，验证未通过，错误次数太多！");
            output.setMsg("账号或密码错误次数太多！");
        }catch(AuthenticationException ae){
            logger.info("账号【" + account +"】进行登录验证，验证未通过，堆栈轨迹如下：！");
            ae.printStackTrace();
            output.setMsg("账号或密码不正确！");
        }
        InvocationContextHolder contextHolder=InvocationContextHolder.getContext();
        Input input=contextHolder.getInput();
        input.setServiceName("sysLoginLogServiceImpl");
        if(currentUser.isAuthenticated()){
            AiPlatformUtil.returnMsgBuild(output,IConstants.SUCCESS,"登录成功",account);
            //验证成功
            SysUser sysUser= (SysUser) currentUser.getPrincipal();
            input.putValue(AiPlatformUtil.PLATFORM_SESSION_USER_SUBJECT, Base64Utils.encodeToString(JSON.toJSONString(sysUser).getBytes()));
            input.setMethod("loginLogSuccess");
        }else {
            //验证失败
            input.setMethod("loginLogFailed");
        }
        input.putValue("msg", output.getMsg());
        //写入登录日志
        super.getControlService().execute(input);
        return output;
    }

    /**
     * 验证码
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @RequestMapping("/kaptcha")
    public void kaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute("vrifyCode", createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
}